// let coordtransform=require('coordtransform');

var MyPlugin = {};
MyPlugin.install = function(Vue) {
	var wx = Vue.wechat;
	console.log("wx:" + wx);
	var runMode = "pc";
	var clientType = "pc";
//	var debug = true;
	var debug = false;
	var errorMsg = "调用参加失败:未知的客户端模式！";
	//	debugger;
	if(isWechat())
		runMode = "wechat";
	else if(isAndroid()) {
		runMode = "app";
		clientType = "android";
	} else if(isIOS()) {
		runMode = "app";
		clientType = "ios";
	}

	// runMode = "wechat";
	console.log("当前模式：" + runMode);

	let myNative = {
		mode: runMode,
		wxConfig: function(res) {
			if(runMode == "app")
				return;
			var appId = res.obj.appId;
			var timestamp = res.obj.timestamp;
			var noncestr = res.obj.noncestr;
			var signature = res.obj.signature;

			wx.ready(function() {
				console.log("微信准备就绪！")
			});

			wx.error(function(res) {
				alert('微信授权失败：' + res.errMsg);
			});

			wx.config({
				debug: false,
				appId: appId, // 必填，企业号的唯一标识，此处填写企业号corpid
				timestamp: timestamp, // 必填，生成签名的时间戳
				nonceStr: noncestr, // 必填，生成签名的随机串
				signature: signature, // 必填，签名，见附录1
				jsApiList: ['chooseImage', 'uploadImage', 'previewImage', 'scanQRCode', 'getLocation'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
			});

		},
		//新建插件时用到的模版
		template: function() {
			return new Promise(function(resolve, reject) {
				switch(runMode) {
					case "wechat":

						break;
					case "app":

						break;
					default:
						console.log("errorMsg");
						reject();
						break;
				}
			})
		},
		//获取地理位置信息
		getGps: function() {
			return new Promise(function(resolve, reject) {
				switch(runMode) {
					case "wechat":
						wx.getLocation({
							type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
							success: function(res) {
								var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
								var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
								var speed = res.speed; // 速度，以米/每秒计
								var accuracy = res.accuracy; // 位置精度
								resolve(res);
							},
							fail: function(error) {
								reject(error);
							}
						});
						break;
					case "app":
						plus.geolocation.getCurrentPosition(function (p) {
							// alert(p.coordsType)
							if (p.coordsType == 'gcj02'){
								resolve({
									"lat": p.coords.latitude,
									"lon": p.coords.longitude
								});
							}else{
								let ress = coordtransform.wgs84togcj02(p.coords.longitude, p.coords.latitude)
								resolve({
									"lat": ress[1],
									"lon": ress[0]
								});
							}
							// let ress = coordtransform.wgs84togcj02(p.coords.longitude, p.coords.latitude)
							// alert(JSON.stringify(p))
							
						}, function (e) {
							plus.nativeUI.toast("Geolocation error: ' + e.message")
							plus.nativeUI.alert("定位失败，请确认您的手机是否打开gps定位！");  
							// alert('Geolocation error: ' + e.message);
						}, { provider: 'amap', enableHighAccuracy: true})
						// plus.geolocation.getCurrentPosition(function(p){
						// 	let ress=coordtransform.wgs84togcj02(p.coords.longitude,p.coords.latitude)
						// 	// alert(JSON.stringify(p))
						// 	resolve({
						// 		"lat":ress[1],
						// 		"lon":ress[0]
						// 	});
						// },function(e){
						// 	alert('Geolocation error: ' + e.message);
						// 	}, { provider: 'amap', enableHighAccuracy: true, coordsType:'gcj02'})
						break;
					default:
						console.log("errorMsg");
						reject();
						break;
				}
			})
		},
		//压缩图片  
        compressImage(url,filename,divid){
			let self=this;
			return new Promise(function(resolve, reject) {
				var name="_doc/upload/"+divid+"-"+filename;//_doc/upload/F_ZDDZZ-1467602809090.jpg  
				plus.zip.compressImage({  
						src:url,//src: (String 类型 )压缩转换原始图片的路径  
						dst:name,//压缩转换目标图片的路径  
						format: 'jpg',
						quality:20,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100  
						overwrite:true,//overwrite: (Boolean 类型 )覆盖生成新文件  
							
					},  
					function(event) {  
						// alert(JSON.stringify(event))
						resolve(event);
						//uploadf(event.target,divid);  
						var path = name;//压缩转换目标图片的路径  
						//event.target获取压缩转换后的图片url路  
					},function(error) {  
						reject();
						plus.nativeUI.toast("压缩图片失败，请稍候再试");  
				});
			})  
        },  
		chooseImgs:function(val){
			return new Promise(function(resolve, reject) {
				switch(runMode) {
					case "wechat":
						console.log(wx);
						resolve({type:'wx',data:''});
						break;
					case "app":
						resolve({type:'app',data:!val});
						break;
					default:
						console.log("errorMsg");
						reject();
						break;
				}
			})
		},
		galleryImg:function(key,id){
			let self=this;
			return new Promise(function(resolve, reject) {
				if(key=='menu1'){
					var cmr = plus.camera.getCamera();
					cmr.captureImage( function ( path ) {
						plus.gallery.save(path);
						plus.nativeUI.showWaiting("正在上传...!");
						// resolve([path]);
						plus.io.resolveLocalFileSystemURL(path,function(entry) {  
							// alert(JSON.stringify(entry))  
							self.compressImage(entry.toLocalURL(),entry.name,id).then(data=>{
								resolve([{'path':data.target,'key':entry.name}]);
							})  
						}, function(e) {  
							plus.nativeUI.toast("读取拍照文件错误：" + e.message);  
						});
					}, function ( e ) {
						plus.nativeUI.toast("取消拍照");
						reject();
					}, {filename:"_doc/camera/",index:1} );
				} else if (key == 'menu2'){
					// 从相册中选择图片
					plus.gallery.pick( function(e){
						var zm=0,imgArr=[];
						plus.nativeUI.showWaiting("正在上传...!");
						function file(){
							plus.io.resolveLocalFileSystemURL(e.files[zm], function(entry) {
								self.compressImage(entry.toLocalURL(),entry.name,id).then(data=>{
									var imgObj={'path':data.target,'key':entry.name}
									imgArr.push(imgObj);
									zm++;
									if(zm<e.files.length){
										file();
									}else{
										// alert('aa'+JSON.stringify(imgArr))
										resolve(imgArr);
									}
								})
							}, function(e) {
								alert(JSON.stringify(e))
							   plus.nativeUI.toast("读取拍照文件错误：" + e.message);
							});
						}
						file();
					}, function ( e ) {
						plus.nativeUI.toast("取消选择图片");
					},{filename: "_doc/camera/",filter:"image",multiple:true,maximum:5,system:false,onmaxed:function(){
						plus.nativeUI.toast('最多只能选择5张图片');
						reject();
					}});// 最多选择3张图片
				}else{
					reject();
				}
			})
		},
		uploader:function(url,data,file,option){
			let self=this;
			return new Promise(function(resolve, reject) {
				switch(runMode) {
					case "wechat":
						console.log(wx);
						
						break;
					case "app":
						option=option||{method: "POST"};
						let taskUploader=plus.uploader.createUpload(url, option, function ( t, status ) {
							// 上传完成
							if ( status == 200 ) { 
								resolve(t, status);
							} else {
								plus.nativeUI.alert( "Upload failed: " + status );
								reject();
							}
						});
						for(var i in file){
							taskUploader.addFile(file[i].path, {key:file[i].key} );
						}
						
						// taskUploader.addFile( "_www/a.doc", {key:"testdoc"} );
						for(var i in data){
							taskUploader.addData(i,data[i].toString());
						}
						taskUploader.addData('token',self.getCache('token'));
						//task.addEventListener( "statechanged", onStateChanged, false );
						taskUploader.start();
						break;
					default:
						console.log("errorMsg");
						reject();
						break;
				}
			})
		},
		getAppVersion(){
			return new Promise(function(resolve, reject) {
				plus.runtime.getProperty(plus.runtime.appid,function(inf){
					resolve(inf.version);
				});
			})
		},
		// 更新应用资源
		installWgt(path) {
			plus.nativeUI.showWaiting("安装wgt文件...");
			plus.runtime.install(path, {}, function() {
				plus.nativeUI.closeWaiting();
				localStorage.setItem('updated',true)
				console.log("安装wgt文件成功！");
				plus.nativeUI.alert("应用资源更新完成！", function() {
					plus.runtime.restart();
				});
			}, function(e) {
				plus.nativeUI.closeWaiting();
				console.log("安装wgt文件失败[" + e.code + "]：" + e.message);
				plus.nativeUI.alert("安装wgt文件失败[" + e.code + "]：" + e.message);
			});
		},
		download:function(url,option,noConfirm){
			let self=this;
			return new Promise(function(resolve, reject) {
				switch(runMode) {
					case "wechat":
						console.log(wx);
						break;
					case "app":
						
						let data={},downUrl=url.indexOf('http')>-1?url:window.location.origin+url;
						data.token=self.getCache('token');
						if(option){
							for(let i in option){
								data[i]=option[i]
							}
						}
						data=JSON.stringify(data)
						// alert(data)
						// alert(downUrl)
						var dtask = plus.downloader.createDownload(downUrl, {method:"POST",data:data}, function ( d, status ) {
							// 下载完成
							if ( status == 200 ) { 
								/*alert(JSON.stringify(d))
								alert( "Download success: " + d.filename );*/
								if(!noConfirm){
									if(confirm(d.filename+'下载成功是否立即打开？')){
										plus.runtime.openFile(d.filename );
										// plus.io.requestFileSystem( plus.io.PUBLIC_DOWNLOADS, function(fs){
										// 	// plus.runtime.openFile(filepath);
										// 	// fs.root是根目录操作对象DirectoryEntry
										// 	fs.root.getFile(d.filename,{create:false}, function(fileEntry){
										// 		fileEntry.getFile()
										// 	});
										// } );
									}
								}
								resolve( d);
							} else {
								alert( "Download failed: " + status ); 
							}  
						});
						// function onStateChanged( download, status ) {
						// 	  alert(status)
							 
							  
						// 	if ( download.state == 4 && status == 200 ) {
						// 		// 下载完成 
						// 		alert( "Download success: " + download.getFileName() );  
						// 	}  
						// }
						// dtask.addEventListener( "statechanged", onStateChanged, false );
						// dtask.setRequestHeader('Content-Type','application/json');
						dtask.start();
						break;
					default:
						window.open(window.location.origin+url)
						console.log("errorMsg");
						reject();
						break;
				}
			})
		},
		//二维码扫一扫
		scan: function() {
			return new Promise(function(resolve, reject) {
				switch(runMode) {
					case "wechat":
						console.log(wx);
						wx.scanQRCode({
							needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
							scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
							success: function(res) {
								resolve(res.resultStr);
							},
							fail: function(error) {
								reject(error);
							}
						});
						break;
					case "app":
						plus.webview.open('./native/plus/barcode_scan.html');
						window.scan = function (res){
//							alert(res);
							resolve(res);
						}
						break;
					default:
						console.log("errorMsg");
						reject();
						break;
				}
			})
		},
		//获取缓存
		getCache: function(key) {
			switch(runMode) {
				case "wechat":
					console.log("微信暂不支持缓存！");
					return "";
					break;
				case "app":
					if(plus){
						console.log(plus.storage.getItem(key));
						return plus.storage.getItem(key);
					}else
						return localStorage[key];
					break;
				default:
					console.log("errorMsg");
					return "";
					break;
			}
		},
		setCache: function(key,value) {
			switch(runMode) {
				case "wechat":
					console.log("微信暂不支持缓存！");
					return "";
					break;
				case "app":
					if(plus){
						console.log(key+","+value);
						return plus.storage.setItem(key,value);
					}else
						return localStorage[key]=value;
					break;
				default:
					console.log("errorMsg");
					return "";
					break;
			}
		},
		exitApp: function() {
			switch(runMode) {
				case "wechat":
					console.log("微信暂不支持缓存！");
					return "";
					break;
				case "app":
//					ClientUtil.exitNoAsk();
					plus.runtime.quit();
					break;
				default:
					console.log("errorMsg");
					return "";
					break;
			}
		},
		//通过摄像头拍照或者录像
		camera: function() {
			return new Promise(function(resolve, reject) {
				switch(runMode) {
					case "wechat":

						break;
					case "app":
						var camerawindow = new CameraWindow();
						camerawindow.mode = "still";
						camerawindow.quality = "high"; //IOS平台，且mode为still支持
						//camerawindow.pwidth = ;
						camerawindow.onCallback = function() {
							if(camerawindow.isSuccess()) {
								alert("照片或视频存放的文件夹路径：" + camerawindow.path);
								alert(camerawindow.value);
								//								document.getElementById(divid).innerHTML = "照片或视频存放的文件夹路径：" + camerawindow.path + "<br/>照片或视频完整路径：" + camerawindow.value;
							}
						};
						camerawindow.startCamera();
						break;
					default:
						console.log("errorMsg");
						reject();
						break;
				}
			})
		},
	}
	Vue.prototype.$native = myNative;
	return myNative;
	//	Vue.native = myNative;
};
//是否微信
function isWechat() {
	let uaInfo = navigator.userAgent;
	let agents = ["MicroMessenger"];
	let flag = false;
	for(let i = 0; i < agents.length; i++) {
		if(uaInfo.indexOf(agents[i]) > 0) {
			console.log("当前为微信环境");
			flag = true;
			break;
		}
	}
	return flag;
};
//是否android
function isAndroid() {
	let uaInfo = navigator.userAgent;
	let agents = ["Android"];
	let flag = false;
	for(let i = 0; i < agents.length; i++) {
		if(uaInfo.indexOf(agents[i]) > 0) {
			flag = true;
			break;
		}
	}
	return flag;
};
//是否ios
function isIOS() {
	let uaInfo = navigator.userAgent;
	let agents = ["iPhone", "iPad", "iPod"];
	let flag = false;
	for(let i = 0; i < agents.length; i++) {
		if(uaInfo.indexOf(agents[i]) > 0) {
			flag = true;
			break;
		}
	}
	return flag;
};
//是否pc
function isPC() {
	let uaInfo = navigator.userAgent;
	let agents = ["Android", "iPhone", "Windows Phone", "iPad", "iPod", "MicroMessenger"];
	let flag = true;
	for(let i = 0; i < agents.length; i++) {
		if(uaInfo.indexOf(agents[i]) > 0) {
			flag = false;
			break;
		}
	}
	return flag;
};

export default MyPlugin;